/**
 * 
 */
package com.feib.stms.action;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.feib.stms.model.Group;
import com.feib.stms.pagination.PaginatedList;
import com.feib.stms.service.GroupService;
import com.feib.stms.util.UserUtil;

/**
 * @title (#)Stms9009ActionBean.java<br>
 * @description 券商資料維護 <br>
 * @author Lion Gao<br>
 * @version 
 * @copyright Far Eastern International Bank Copyright (c) 2012<br>
 * @2012/05/28 create by Jimmy Liu<br>
 *
 */
public class Stms9009ActionBean extends BaseActionBean 
{
	private static final long serialVersionUID = -3360927795653829350L;

	private static final String DEFAULT_JSP = "/WEB-INF/views/stms9009/stms9009.jsp";
	private static final String DETAIL_JSP = "/WEB-INF/views/stms9009/stms9009Detail.jsp";
	private static final String CREATE_JSP = "/WEB-INF/views/stms9009/stms9009Create.jsp";
	
	/*畫面sortHeader傳回來的值*/
	private static List<String> SORT_KEYS = new ArrayList<String>();
	static{
		SORT_KEYS.add("groupNo".toLowerCase());
		SORT_KEYS.add("groupName".toLowerCase());
		SORT_KEYS.add("ubm".toLowerCase());
		SORT_KEYS.add("contactName".toLowerCase());
		SORT_KEYS.add("contactTelno".toLowerCase());
		SORT_KEYS.add("contactCellno".toLowerCase());
		SORT_KEYS.add("contactEmail".toLowerCase());
		SORT_KEYS.add("groupAddress".toLowerCase());
	}

	/*使用SORT_KEYS作key值取得對應的資料庫欄位名稱*/
	private static Map<String,String> SORT_FIELD =  new HashMap<String, String>();
	static{
		SORT_FIELD.put("groupNo".toLowerCase(), "GROUP_NO");
		SORT_FIELD.put("groupName".toLowerCase(), "CONTACT_NAME");
		SORT_FIELD.put("ubm".toLowerCase(), "UBM");
		SORT_FIELD.put("contactName".toLowerCase(), "CONTACT_NAME");
		SORT_FIELD.put("contactTelno".toLowerCase(), "CONTACT_TELNO");
		SORT_FIELD.put("contactCellno".toLowerCase(), "CONTACT_CELLNO");
		SORT_FIELD.put("contactEmail".toLowerCase(), "CONTACT_EMAIL");
		SORT_FIELD.put("groupAddress".toLowerCase(), "GROUP_ADDRESS");
	}

	/** 
	 * 查詢條件-券商代號
	 */
	private String qryGroupNoForm;
	
	/** 
	 * 查詢條件-券商名稱
	 */
	private String qryGroupNameForm;
	
	 /**
     * 查詢結果(多筆)
     */
    private PaginatedList<Group> queryResult;
	
    /**
     * 更新-綁定查詢條件
     */
    @Validate( required=true, on={"doViewDetail"})
    private Long qryGroupPk;
    
    /**
     * 更新-綁定bean
     */
    private Group editGroup;
    
    /**
     * 新增-綁定bean
     */
    private Group createGroup;
    
	@SpringBean("groupService")
	private GroupService groupService;
	
	/**
	 * 執行結果訊息
	 */
	private String message;
	
	/**
	 * 新增權限
	 */
	private Boolean created = true;
	
	 /**
     * 標記新增或修改
     */
    private String operation;

	@DontBind
	@DefaultHandler
	public Resolution doDefault()
	{
		logger.debug("Enter doDefault mehtod.");
		//設置權限
		dealRight();
		return new ForwardResolution(DEFAULT_JSP); 
	}

	/**
	 * 查詢
	 * @return
	 */
	public Resolution doQuery()
	{
		logger.debug("Enter doQuery mehtod.");
		//設置權限
		dealRight();
		/* 設定換頁、排序等條件*/
		String sortCriterion = "groupNo";
		int sortDirection = 1;
		PaginatedList<Group> qryCondition = new PaginatedList<Group>();
		if (null != queryResult)
		{	
			//畫面傳入的排序字段
			sortCriterion = queryResult.getSortCriterion();
			sortDirection = queryResult.getSortDirection();
			//分頁
			qryCondition.setPageNumber(queryResult.getPageNumber());
			qryCondition.setPageSize(queryResult.getPageSize());
			//將畫面傳入的排序字段轉換為資料庫對應的字段
			String StringSortCriterion = SORT_FIELD.get(sortCriterion.toLowerCase());
			//設置排序
			qryCondition.setSortCriterion(StringSortCriterion);
			qryCondition.setSortDirection(sortDirection);
			logger.debug(" qryCondition:sortCriterion={}  sortDirection={} ", new Object[]{qryCondition.getSortCriterion(), qryCondition.getSortDirection()});
			
		}
		/*沒有設定排序就以第一欄作排序條件*/
		if (null == queryResult || StringUtils.isEmpty(queryResult.getSortCriterion()) || !SORT_KEYS.contains(queryResult.getSortCriterion().toLowerCase()))
		{
			qryCondition.setSortCriterion(SORT_FIELD.get(SORT_KEYS.get(0)));
		}
		
		/* 設定查詢條件*/
		Group qryGroup = new Group();
		qryGroup.setGroupNo(qryGroupNoForm);
		qryGroup.setGroupName(qryGroupNameForm);
		//調用service,到資料庫撈取DB
		this.queryResult = groupService.findForPaginatedListByGroup(qryGroup, qryCondition);

		if (null == this.queryResult)
			this.queryResult = qryCondition;
		
		queryResult.setSortCriterion(sortCriterion);
		queryResult.setSortDirection(sortDirection);

		if (CollectionUtils.isEmpty(this.queryResult.getPaginatedList()))
			this.message = "查無資料！";

		return new ForwardResolution(DEFAULT_JSP); 
	}

	/**
	 * 查看券商維護資料
	 * @return
	 */
	public Resolution doUpdate()
	{
		logger.debug("Enter doUpdate mehtod.");
		this.operation = "update";
		this.editGroup = groupService.getByGroupPk(qryGroupPk);
		return new ForwardResolution(DETAIL_JSP); 
	}
	
	 /**
     * 跳轉新增畫面
     * @return
     */
    public Resolution doCreate()
    {	
    	logger.debug("Enter doCreate mehtod.");
    	this.operation = "create";
    	return new ForwardResolution(CREATE_JSP); 
    }
    
	 /**
     * 確認
     * @return
     */
    public Resolution doSave()
    {	
    	logger.debug("Enter doSave mehtod.");
    	if(this.operation != null && this.operation.equals("create")){
    		//查詢券商代號是否重複
            int countResult = groupService.countGroupNo(createGroup.getGroupNo());
            if(countResult > 0){
            	message = "新增失敗,券商代號重複!";
            }else{
            	int insertCount = groupService.saveGroup(createGroup);
            	message = insertCount > 0?"新增成功！":"新增失敗!";
            	if(insertCount > 0){//新增成功，則跳轉到查詢畫面
            		return doQuery();
            	}
            }
        	return new ForwardResolution(CREATE_JSP); 
    	}else if(this.operation != null && this.operation.equals("update")){
    		//查詢券商代號是否重複
            int countResult = groupService.countGroupNo(editGroup.getGroupPk(), editGroup.getGroupNo());
            if(countResult > 0){
            	message = "修改失敗,券商代號重複!";
            }else{
            	int insertCount = groupService.updateGroup(editGroup);
            	message = insertCount > 0?"修改成功！":"修改失敗!";
            	if(insertCount > 0){//更新成功，則跳轉到查詢畫面
            		return doQuery();
            	}
            }
            return new ForwardResolution(DETAIL_JSP); 
    	}
    	return doQuery();
    }
    
    /**
     * 取消
     * @return
     */
    public Resolution doCancel()
    {
    	logger.debug("Enter doCancel mehtod.");
    	return doQuery();
    }
    
	/**
	 * @return editGroup
	 */
	public Group getEditGroup() {
		return editGroup;
	}

	/**
	 * @param editGroup 的設定的 editGroup
	 */
	public void setEditGroup(Group editGroup) {
		this.editGroup = editGroup;
	}

	/**
	 * @return message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message 的設定的 message
	 */
	public void setMessage(String message) {
		this.message = message;
	}
	
	/**
	 * @return qryGroupPk
	 */
	public Long getQryGroupPk() {
		return qryGroupPk;
	}

	/**
	 * @param qryGroupPk 的設定的 qryGroupPk
	 */
	public void setQryGroupPk(Long qryGroupPk) {
		this.qryGroupPk = qryGroupPk;
	}

	/**
	 * @return qryGroupNameForm
	 */
	public String getQryGroupNameForm() {
		return qryGroupNameForm;
	}

	/**
	 * @param qryGroupNameForm 的設定的 qryGroupNameForm
	 */
	public void setQryGroupNameForm(String qryGroupNameForm) {
		this.qryGroupNameForm = qryGroupNameForm;
	}

	/**
	 * @return qryGroupNoForm
	 */
	public String getQryGroupNoForm() {
		return qryGroupNoForm;
	}

	/**
	 * @param qryGroupNoForm 的設定的 qryGroupNoForm
	 */
	public void setQryGroupNoForm(String qryGroupNoForm) {
		this.qryGroupNoForm = qryGroupNoForm;
	}

	/**
	 * @return queryResult
	 */
	public PaginatedList<Group> getQueryResult() {
		return queryResult;
	}

	/**
	 * @param queryResult 的設定的 queryResult
	 */
	public void setQueryResult(PaginatedList<Group> queryResult) {
		this.queryResult = queryResult;
	}

	/**
	 * @return createGroup
	 */
	public Group getCreateGroup() {
		return createGroup;
	}

	/**
	 * @param createGroup 的設定的 createGroup
	 */
	public void setCreateGroup(Group createGroup) {
		this.createGroup = createGroup;
	}

	/**
	 * @return created
	 */
	public Boolean getCreated() {
		return created;
	}

	/**
	 * @param created 的設定的 created
	 */
	public void setCreated(Boolean created) {
		this.created = created;
	}

	/**
	 * @return operation
	 */
	public String getOperation() {
		return operation;
	}

	/**
	 * @param operation 的設定的 operation
	 */
	public void setOperation(String operation) {
		this.operation = operation;
	}
	
	/*
	 * 進行權限判定，銀行使用者維護券商資料，包含查詢、新增、修改等作業。
	 * 券商業者修改本身券商基本資料，包含查詢、修改等作業。
	 */
	protected void dealRight(){
		if(UserUtil.isBankGroup()){
			created = true;
		}else if(!UserUtil.isBankGroup()){
			created = false;
		}
	}
}
